package org.zachary.creditbusiness.hotel.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * 调用 Python 脚本，仅提取并返回 occupancy 预测的原始 JSON 字符串
 */
public class ExecPythonProcess {

    /**
     * 调用 Python 脚本并返回 JSON 字符串
     *
     * @param pythonExe    Python 解释器名称或路径（如 "python3"）
     * @param scriptPath   脚本的绝对文件系统路径
     * @param hotelId      酒店 ID
     * @param dateStr      当前时间字符串，含时区
     * @param hotelDataDir hoteldata 目录绝对路径
     * @return 预测结果 JSON
     */
    public static String execPython(
            String pythonExe,
            String scriptPath,
            String hotelId,
            String dateStr,
            String hotelDataDir) {

        try {
            ProcessBuilder pb = new ProcessBuilder(
                    pythonExe,
                    scriptPath,
                    hotelId,
                    dateStr,
                    hotelDataDir
            );
            pb.redirectErrorStream(true);
            Process process = pb.start();

            String output = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))
                    .lines().collect(Collectors.joining());

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException(
                        "Python 脚本退出码=" + exitCode + "，输出=" + output);
            }

            // 提取 JSON 部分
            String begin = "occupancys-begin=>";
            String end   = "occupancys-end";
            int i1 = output.indexOf(begin);
            int i2 = output.indexOf(end);
            if (i1 < 0 || i2 < 0 || i2 <= i1) {
                throw new RuntimeException("未找到预测标记，输出=" + output);
            }
            return output.substring(i1 + begin.length(), i2);

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("调用 Python 脚本失败", e);
        }
    }
}
